package com.romadan.gui.builder;

import java.io.File;
import java.net.URL;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.romadan.general.settings.PConstants;
import com.romadan.gui.controller.AbstractController;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class ApplicationBuilder extends Application {

	protected String dialogFXML;
	protected String dialogName;
	
	public ApplicationBuilder(){
		dialogFXML = null;
		dialogName = "";
	}
	
	public ApplicationBuilder(String dialogFXML, String dialogName){
		this.dialogFXML = dialogFXML;
		this.dialogName = dialogName;
	}
	
	public void start(Stage stage) throws Exception {
		
		Parameters params = this.getParameters();
		List<String> val = params.getRaw();
		if(CollectionUtils.isNotEmpty(val)){
			dialogName = val.get(0);
			dialogFXML = val.get(1);
		}else{
			throw new IllegalArgumentException("Runtime parameters don't set to dialog");
		}
		
		File f = new File(dialogFXML);
    	URL fxmlURL = f.toURL();
    	
    	if(fxmlURL == null){
    		throw new IllegalArgumentException("FXML file cannot be load");
    	}
    	AnchorPane mainPane = FXMLLoader.load(fxmlURL);
    	Scene scene = new Scene(mainPane);
    	stage.setScene(scene);
    	stage.setTitle(dialogName);
    	stage.show();
    	stage.setHeight(PConstants.HEIGHT_WINDOW_EXPANDED);
    	AbstractController.stage = stage;
	}
	
	public void showApplication(){
		if(dialogName == null) dialogName = "";
		if(dialogFXML == null) throw new IllegalArgumentException("FXML file didn't assign to dialog");
		
		Application.launch(ApplicationBuilder.class, new String[]{dialogName, dialogFXML});
	}
}
